import 'dart:convert';
import 'dart:io';

class FileTransfer {
  ConnectionTask<Socket> _socketTask;
  File _file;
  static ServerSocket _serverSocket;
  static listen() async {
    if (_serverSocket == null) {
      _serverSocket = await ServerSocket.bind(InternetAddress.anyIPv4, 33333);
    }
    _serverSocket.isBroadcast;
    await for (var socket in _serverSocket.asBroadcastStream()) {
      _accept(socket);
    }
  }

  static _accept(Socket socket) async {
    await for (var data in socket.asBroadcastStream()) {
      var str=Utf8Codec().decode(data,allowMalformed: true);
      print(["file",str]);
    }
  }

   Future<FileTransfer> file(File file) async{
    _file=file;
    if(_socketTask==null){
      _socketTask =await Socket.startConnect(InternetAddress("194.168.1.5"), 33333);
    }
    return this;
  }
  void toClient() async{
    var socket=await _socketTask.socket;
    socket.addStream(_file.openRead());
  }
}
